package com.jia.lightrailsystem

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.jia.lightrailsystem.bean.DeviceStatus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import org.json.JSONObject
import priv.songxusheng.easystorer.EasyStorer

class MainVM(application: Application) : AndroidViewModel(application) {
    private val _id = MutableLiveData<Int>()
    val id: LiveData<Int> = _id
    private val _deviceStatus = MutableLiveData(DeviceStatus())
    val deviceStatus: LiveData<DeviceStatus> = _deviceStatus
    private val _connectionStatus = MutableStateFlow(false)
    val connectionStatus: StateFlow<Boolean> = _connectionStatus
    private var flowId =  0

    fun updateConnectionStatus(connected: Boolean) {
        _connectionStatus.value = connected
    }
//    init {
//        initUart()
//    }

    fun initUart() {
        try {
            UartUtil.openUart("/dev/ttyZC0", 9600)
        }catch (e : Exception){
            println(e.message+"串口打开失败")
            return
        }

        viewModelScope.launch(Dispatchers.IO) {
            UartUtil.onDataReceived().collect { s ->
                delay(500)
                handleData(s)
            }
        }
    }
    fun updateDeviceStatus(update: (DeviceStatus) -> Unit) {
        val current = _deviceStatus.value ?: DeviceStatus()
        update(current)
        _deviceStatus.postValue(current)
    }
    private suspend fun handleData(data: String) {
        Log.d("串口数据",data)
        try {
            val control = JSONObject(data)
            val cmd = control.optString("cmd")

            when {
                control.has("dukaqi") && cmd == "status" ->{
                    val data = JSONObject(control.getString("dukaqi")).optString("data")
                    Http.readRfid(data){it->
                        flowId = it.flow_id
                    }
                }
                control.has("cheliang") && cmd == "status" -> {
                    val zt = JSONObject(control.getString("cheliang")).optString("zt")
                    if (zt == "1") {
                        updateDeviceStatus { it.car = "就绪" }
                        updateDeviceStatus { it.overallStatus = "检查中" }
                        Http.createNote(31,flowId) {code->
                            IdStorer.id = code.id//设置密码
                            _id.postValue(code.id)
//                            SocketClient.socket?.let { SocketClient.sendData(it, code.type.toString())}
                            SocketClient.sendData(code.type.toString())
                        }
                    }else{
                        updateDeviceStatus { it.car = "未就绪" }
                    }
                }

                control.has("dianji") && cmd == "status" -> {
                    Log.d("dianji:","~~~")
                    val zt = JSONObject(control.getString("dianji")).optString("zt")
                    Log.d("dianji:","~~~${zt}")
                    if (zt == "wc") {
                        updateDeviceStatus { it.moving = "移动中" }
                        Http.updateNote(IdStorer.id, "34","") {code->
//                            SocketClient.socket?.let { SocketClient.sendData(it, code.type.toString()) }
                            SocketClient.sendData(code.type.toString())

                        }
                    }
                }

                control.has("penmaji") && cmd == "status" -> {

                    val zt = JSONObject(control.getString("penmaji")).optString("zt")
                    if (zt == "wc") {
                        updateDeviceStatus { it.printer = "已喷码" }
                        Http.updateNote(IdStorer.id ,"38","") {code->
//                            SocketClient.socket?.let { SocketClient.sendData(it, code.type.toString()) }
                            updateDeviceStatus { it.overallStatus = "检查完毕" }
//                            UartUtil.onDataSend(code.penmaji.toString())
                            updateDeviceStatus { it.statistics = code.statistics}
                        }
                    }
                }

                control.has("dengguang") && cmd == "status" -> {
                    val obj = JSONObject(control.getString("dengguang"))
                    val sw = obj.optString("sw")
                    val zt = obj.optString("zt")
                    if (sw == "K"&&zt=="wc")updateDeviceStatus { it.light = "已开" }
                    if (sw == "G"&&zt=="wc")updateDeviceStatus { it.light = "未开" }
                    if (zt == "wc") {
                        val deng = if (sw == "K") "33" else "32"
                        LogUtils.d("$deng,${IdStorer.id}")
                        Http.updateNote(IdStorer.id, deng,"") {code->
                            updateDeviceStatus { it.overallStatus = "检查完毕" }
//                            SocketClient.socket?.let { SocketClient.sendData(it, code.type.toString()) }
                            SocketClient.sendData(code.type.toString())
                        }
                    }
                }
            }

        } catch (e: Exception) {
        }
    }

    fun initSocket(viewModel: MainVM) {

        val photoPort = EasyStorer.get("photoPort", "")
        val photoIp = EasyStorer.get("photoIp", "")
        val serverIp = EasyStorer.get("serverIp", "")
        if (photoPort.isEmpty()){
            ToastUtils.showShort("请配置相机地址")
            return
        }
        if (photoIp.isEmpty()){
            ToastUtils.showShort("请配置相机端口")
            return
        }
        if (serverIp.isEmpty()){
            ToastUtils.showShort("请配置服务器地址")
            return
        }
        SocketClient.init( photoIp, photoPort.toInt(),viewModel)
        Log.d("SocketClient","${photoIp}~~~${photoPort}")
        Http.httpInit(serverIp)
    }
}
